<template>
  <div class="home-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20">
      <!-- 每日订单数【完单数量】 -->
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日订单数</span>
              <el-tag type="success">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ statisticalData.todayOrderCount }}</h2>
            <div class="comparison">
              较昨日 <span :class="statisticalData.todayOrderCountPercentage > 0 ? 'down' : 'up'">
                {{ statisticalData.todayOrderCountPercentage.toFixed(2) }} % 
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 每日销售额【完单数】 -->
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日销售额</span>
              <el-tag type="warning">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <h2>￥{{ statisticalData.todayTotalPrice.toFixed(2) }}</h2>
            <div class="comparison">
              较昨日 <span :class="statisticalData.todayTotalPricePercentage > 0 ? 'down' : 'up'">
                {{ statisticalData.todayTotalPricePercentage.toFixed(2) }} %
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 每日新增用户【每日注册用户】 -->
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>新增用户</span>
              <el-tag type="info">今日</el-tag>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ statisticalData.todayRegisterUserCount }}</h2>
            <div class="comparison">
              较昨日 <span :class="statisticalData.todayRegisterUserCountPercentage > 0 ? 'down' : 'up'">
                {{ statisticalData.todayRegisterUserCountPercentage.toFixed(2) }} %
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 库存数量预警 -->
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>库存预警</span>
              <el-tag type="danger">紧急</el-tag>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ statisticalData.todayOutStockProductCount }}</h2>
            <div class="comparison">
              需要补货的商品数量
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span>销售趋势</span>
                <el-radio-group v-model="chartType" size="small">
                  <el-radio-button label="bar">柱状图</el-radio-button>
                  <el-radio-button label="line">折线图</el-radio-button>
                </el-radio-group>
              </div>
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="salesChartRef"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="rank-card">
          <template #header>
            <div class="card-header">
              <span>热销商品排行</span>
            </div>
          </template>
          <el-scrollbar height="300px">
            <el-table :data="statisticalData.hotProducts" style="width: 100%" :show-header="false" :height="300">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="name" />
              <el-table-column prop="monthlySales" width="80" align="right" />
            </el-table>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, onUnmounted, computed } from 'vue';
import * as echarts from 'echarts'
import { StatisticalData } from '@/models/homeModel';
import { useCounterSotre } from '@/store/counter';

// 图表对象
const salesChartRef = ref<HTMLElement>()
let salesChart: echarts.ECharts | null = null
// 图表类型【柱状图|折线图】
const chartType = ref("bar")
// 图标的时间轴【周|月|年】
const timeRange = ref("week")
// 统计数据
const store = useCounterSotre()
const statisticalData = computed<StatisticalData>(() => {return store.statisticalData}) 

onMounted(() => {
  // 初始化图表
  setTimeout(() => initChart(), 500)
  // 监听窗口改变
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 关闭图表
  salesChart?.dispose()
  // 取消监听窗口改变
  window.removeEventListener('resize', handleResize)
})

// 初始化图表
const initChart = () => {
  if (salesChartRef.value) {
    salesChart = echarts.init(salesChartRef.value)
    salesChart.setOption(getChartOption(timeRange.value))
  }
}

// 处理窗口大小变化
const handleResize = () => {
  salesChart?.resize()
}

// 监听图表类型变化
watch(chartType, () => {
  if (salesChart) {
    salesChart.setOption(getChartOption(timeRange.value))
  }
})

// 处理时间范围变化
const handleTimeRangeChange = (value: string) => {
  if (salesChart) {
    salesChart.setOption(getChartOption(value))
  }
}

// 图表配置
const getChartOption = (range: string) => {
  const { xData, yData } = generateData(range)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: chartType.value === 'line' ? 'line' : 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '销售额(元)',
      axisLine: {
        show: true
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '销售额',
        type: chartType.value,
        data: yData,
        // 柱状图样式
        ...(chartType.value === 'bar' ? {
          barWidth: '60%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          }
        } :
          // 折线图样式
          {
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF',
              borderWidth: 2,
              borderColor: '#fff'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64,158,255,0.3)' },
                { offset: 1, color: 'rgba(64,158,255,0.1)' }
              ])
            }
          })
      }
    ]
  }
}

// 生成模拟数据
const generateData = (range: string) => {
  let xData: string[] = []
  let yData: number[] = []

  switch (range) {
    case 'week':
      xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      yData = statisticalData.value.weekDayPrice
      break
    case 'month':
      xData = Array.from({ length: statisticalData.value.monthDayPrice.length }, (_, i) => `${i + 1}日`)
      yData = statisticalData.value.monthDayPrice
      break
    case 'year':
      xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      yData = statisticalData.value.yearMonthPrice
      break
  }

  return { xData, yData }
}
</script>

<style scoped>
.home-container {
  height: 100%;
  padding: 0px 10px;
  overflow: auto;
}

.el-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

.card-content h2 {
  margin: 10px 0;
  font-size: 28px;
  color: #303133;
}

.comparison {
  font-size: 14px;
  color: #909399;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.chart-row {
  margin-top: 20px;
}

.chart-card,
.rank-card {
  height: 400px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

:deep(.el-card__body) {
  padding: 10px;
}

:deep(.el-table) {
  border: none;
}

:deep(.el-table::before) {
  height: 0;
}

:deep(.el-table__row) {
  height: 50px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

/* 优化图表卡片样式 */
.chart-card {
  height: 400px;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left span {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-radio-group) {
  margin-left: 16px;
}
</style>